package com.gitee.minimalismstyle.fresh.sys.api.validate

import com.gitee.minimalismstyle.fresh.common.core.exception.MessageException
import com.gitee.minimalismstyle.fresh.common.core.validate.ValidateResult
import com.gitee.minimalismstyle.fresh.common.core.validate.ValueValidate
import com.gitee.minimalismstyle.fresh.sys.api.service.SysKeyValueService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class KeyValueValidate() : ValueValidate {

    @Autowired
    lateinit var sysKeyValueService: SysKeyValueService

    override fun check(value: Any?, params: String?): ValidateResult {
        return if(value == null || value.equals("")){
            ValidateResult(true)
        } else {
            if(params.isNullOrBlank()){
                throw MessageException(message = "请设置键路径")
            }else{
                val dicts = sysKeyValueService.findByParentKeyPath(params).get()
                if(dicts.isNullOrEmpty()){
                    throw MessageException(message = "键路径不存在")
                }else{
                    if(dicts.any { value.equals(it.value) }){
                        ValidateResult(true)
                    }else{
                        ValidateResult(false, "不合法的")
                    }
                }
            }
        }
    }
}